class Commitment {
  static PEDDING = "待定";
  static FULFILLED = "成功";
  static REJECTED = "失败";
  constructor(func) {
    this.status = Commitment.PEDDING;
    // result 代表传入的值
    this.result = null;
    this.resolveCallbacks = [];
    this.rejectCallbacks = [];
    // 这个是因为 在原生promise中 throw抛出异常是会被reject捕获的
    try {
      func(this.resolve.bind(this), this.reject.bind(this));
    } catch {
      this.reject(this.result);
    }
  }
  resolve(result) {
    setTimeout(() => {
      if (this.status == Commitment.PEDDING) {
        this.status = Commitment.FULFILLED;
        this.result = result;
        this.resolveCallbacks.forEach((callback) => {
          callback(this.result);
        });
      }
    });
  }
  reject(result) {
    setTimeout(() => {
      if (this.status == Commitment.PEDDING) {
        this.status = Commitment.REJECTED;
        this.result = result;
        this.rejectCallbacks.forEach((callback) => {
          callback(this.result);
        });
      }
    });
  }
  then(onFULFILLED, onREJECTED) {
    return new Commitment((resolve, reject) => {
      // 下面两行是因为 如果then里面传入的不是函数 会进行处理
      onFULFILLED = typeof onFULFILLED === "function" ? onFULFILLED : () => {};
      onREJECTED = typeof onREJECTED === "function" ? onREJECTED : () => {};
      // 如果是待定状态 例如 setTimeout 中导致resolve没有执行 然后去执行了 then里面的函数 此时状态为PEDDINIG
      //所以 会将此时then里面的函数保存到对应的数组中 当执行到resolve时 会去执行相应的函数
      if (this.status == Commitment.PEDDING) {
        this.resolveCallbacks.push(onFULFILLED);
        this.rejectCallbacks.push(onREJECTED);
      }
      if (this.status == Commitment.FULFILLED) {
        onFULFILLED(this.result);
      }
      if (this.status == Commitment.REJECTED) {
        onREJECTED(this.result);
      }
    });
  }
}
let commitment = new Commitment((resolve, reject) => {
  console.log(1);
  console.log(2);
  resolve("success");
  console.log(3);
});
commitment.then(
  (res) => {
    console.log(res);
  },
  (res) => {
    console.log(res);
  }
);
console.log(111);
